const { v4: uuidv4 } = require('uuid');
const fs = require('fs');
const path = require('path');
const config = require('../config');

// 模拟数据库
const STRATEGIES_FILE = path.join(__dirname, '../data/strategies.json');

// 确保数据目录存在
const ensureDataDirExists = () => {
  const dataDir = path.join(__dirname, '../data');
  if (!fs.existsSync(dataDir)) {
    fs.mkdirSync(dataDir);
  }
};

// 初始化策略数据
const initStrategies = () => {
  ensureDataDirExists();
  if (!fs.existsSync(STRATEGIES_FILE)) {
    fs.writeFileSync(STRATEGIES_FILE, JSON.stringify([]));
  }
};

// 获取所有策略
exports.getStrategies = () => {
  initStrategies();
  const data = fs.readFileSync(STRATEGIES_FILE, 'utf8');
  return JSON.parse(data);
};

// 根据ID获取策略
exports.getStrategyById = (id) => {
  const strategies = exports.getStrategies();
  return strategies.find(strategy => strategy.id === id);
};

// 创建策略
exports.createStrategy = (strategyData) => {
  const strategies = exports.getStrategies();
  const newStrategy = {
    id: uuidv4(),
    name: strategyData.name,
    description: strategyData.description,
    symbol: strategyData.symbol,
    interval: strategyData.interval,
    parameters: strategyData.parameters || [],
    code: strategyData.code || '',
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
    status: 'inactive' // inactive, active, backtesting
  };
  strategies.push(newStrategy);
  fs.writeFileSync(STRATEGIES_FILE, JSON.stringify(strategies, null, 2));
  return newStrategy;
};

// 更新策略
exports.updateStrategy = (id, strategyData) => {
  let strategies = exports.getStrategies();
  const index = strategies.findIndex(strategy => strategy.id === id);
  if (index === -1) return null;

  strategies[index] = {
    ...strategies[index],
    ...strategyData,
    updatedAt: new Date().toISOString()
  };

  fs.writeFileSync(STRATEGIES_FILE, JSON.stringify(strategies, null, 2));
  return strategies[index];
};

// 删除策略
exports.deleteStrategy = (id) => {
  let strategies = exports.getStrategies();
  const initialLength = strategies.length;
  strategies = strategies.filter(strategy => strategy.id !== id);
  if (strategies.length === initialLength) return false;

  fs.writeFileSync(STRATEGIES_FILE, JSON.stringify(strategies, null, 2));
  return true;
};

// 回测策略
exports.backtestStrategy = async (id, backtestParams) => {
  const strategy = exports.getStrategyById(id);
  if (!strategy) throw new Error('策略不存在');

  // 模拟回测过程
  // 在实际应用中，这里会调用专门的回测引擎
  console.log(`开始回测策略: ${strategy.name}`);
  console.log('回测参数:', backtestParams);

  // 模拟回测结果
  const backtestResult = {
    id: uuidv4(),
    strategyId: id,
    startTime: backtestParams.startTime || new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(),
    endTime: backtestParams.endTime || new Date().toISOString(),
    initialBalance: backtestParams.initialBalance || 10000,
    finalBalance: Math.random() * 5000 + 10000,
    totalProfit: 0,
    profitRate: 0,
    maxDrawdown: Math.random() * 10,
    winRate: Math.random() * 50 + 30,
    totalTrades: Math.floor(Math.random() * 100) + 10,
    winningTrades: 0,
    losingTrades: 0,
    netProfit: 0,
    // 模拟净值曲线数据
    equityCurve: Array.from({ length: 30 }, (_, i) => ({
      time: new Date(Date.now() - (30 - i) * 24 * 60 * 60 * 1000).toISOString(),
      value: 10000 + Math.random() * 3000 - 1000
    })),
    // 模拟每日收益数据
    dailyReturns: Array.from({ length: 30 }, (_, i) => ({
      date: new Date(Date.now() - (30 - i) * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      return: (Math.random() * 4 - 2).toFixed(2)
    }))
  };

  // 计算派生指标
  backtestResult.totalProfit = backtestResult.finalBalance - backtestResult.initialBalance;
  backtestResult.profitRate = (backtestResult.totalProfit / backtestResult.initialBalance * 100).toFixed(2);
  backtestResult.winningTrades = Math.floor(backtestResult.totalTrades * backtestResult.winRate / 100);
  backtestResult.losingTrades = backtestResult.totalTrades - backtestResult.winningTrades;
  backtestResult.netProfit = backtestResult.totalProfit;

  // 保存回测结果
  const backtestService = require('./backtest');
  await backtestService.saveBacktestResult(backtestResult);

  return backtestResult;
};

// 启动策略
exports.startStrategy = (id) => {
  const strategy = exports.getStrategyById(id);
  if (!strategy) throw new Error('策略不存在');

  // 模拟启动策略
  console.log(`启动策略: ${strategy.name}`);
  exports.updateStrategy(id, { status: 'active' });

  // 在实际应用中，这里会启动一个后台进程来运行策略

  return { success: true, message: `策略 ${strategy.name} 已启动` };
};

// 停止策略
exports.stopStrategy = (id) => {
  const strategy = exports.getStrategyById(id);
  if (!strategy) throw new Error('策略不存在');

  // 模拟停止策略
  console.log(`停止策略: ${strategy.name}`);
  exports.updateStrategy(id, { status: 'inactive' });

  // 在实际应用中，这里会停止运行策略的后台进程

  return { success: true, message: `策略 ${strategy.name} 已停止` };
};